import { API_CONFIG, config } from "../../config"
const app = getApp()
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		images: {},
		top: 0, // 导航条距离顶部的像素
		height: 0, // 顶部导航条的高度
		btnText: "立即领取",
		isShowPage: false,
		activityStyle: `
    `,
		bgImage: "",
		avatar: "",
		activityId: "", // 活动id(字符串)
		activityIdNumber: "", // 活动id(数字)
		appMsg: {
			show: false,
			type: "none",
		},
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		console.log("活动页面初始参数为:", options)
		const { top, height } = wx.getMenuButtonBoundingClientRect()
		this.setData({
			top,
			height,
		})
		// 解析小程序码参数
		const { scene } = options
		// 拿到活动id(数字)和队长id
		const { a, u } = app.parseScene(decodeURIComponent(scene))
		this.data.activityIdNumber = a
		this.data.captainId = u
		this.getElements(a, u)
	},
	onUnload() {
		app.globalData.activityData = {}
	},
	/**
	 * @see 获取元素
	 */
	getElements(id, u) {
		wx.showLoading({ title: "加载中" })
		const { isCollect } = app.globalData.activityData
		app.globalData.activityData.id = id // 数字活动id
		app.globalData.activityData.captainId = u // 队长id
		// 获取字符串id
		wx.$API["eventConfiguration/getManageActivityOne"]({ id, isCollect })
			.then((res) => {
				return new Promise((resolve) => {
					if (!res.data.length) {
						wx.showToast({
							title: "暂无数据",
							icon: "none",
						})
						return
					}
					const { activityId } = res.data[0]
					this.data.activityId = activityId
					this.addData()
					app.globalData.activityData.activityId = activityId
					resolve()
				})
			})
			.then(() => {
				const { activityId } = this.data // 字符串活动id
				wx.$API["eventConfiguration/getElements"]({
					activityId,
					eIndex: [1, 2],
				})
					.then((res) => {
						const { data } = res
						if (data.length < 1) {
							wx.hideLoading()
							this.setData({
								appMsg: {
									type: "err",
									show: true,
								},
							})
							return
						}
						const { staticUrl } = API_CONFIG

						let btnStyle = {} // 按钮属性
						let shareConfig = {} // 分享有礼配置
						data.forEach((item) => {
							// 不知道为什么,对象里面的json串不能直接转 例如:JSON.parse(item.content)会报错,需要用一个变量先存着再转,神奇!
							let str = item.content
							switch (item.eindex) {
								case 1:
									btnStyle = JSON.parse(str)
									break
								case 2:
									shareConfig = JSON.parse(str)
									break
								default:
									break
							}
						})
						const { button, bgImage } = shareConfig
						// const {
						//   endColor, // 渐变结束颜色
						//   shadowColor, // 阴影颜色
						//   startColor, // 渐变开始颜色,无渐变时为背景颜色
						//   borderColor,// 边框颜色
						//   transparency, // 透明度
						//   isGradient, // 是否开启渐变
						// } = btnStyle
						btnStyle = this.returnBtnStyle({ ...btnStyle })
						wx.setStorage({
							key: "activityBtnStyle",
							data: btnStyle,
						})
						this.setData({
							activityStyle: btnStyle,
							isShowPage: true,
							btnText: button,
							bgImage: staticUrl + bgImage,
						})
						wx.hideLoading()
					})
					.catch((error) => {
						wx.showToast({
							title: error,
							icon: "none",
							duration: 2000,
						})
						console.log("eventConfiguration/getElements 获取元素错误!", error)
					})
			})
			.catch((error) => {
				wx.hideLoading()
				wx.showToast({
					title: error,
					icon: "none",
				})
				const token = wx.getStorageSync("token")
				if (error === "该学校没有活动" && token) {
					setTimeout(() => {
						wx.switchTab({
							url: "/pages/home/index",
						})
					}, 2000)
					return
				}
				this.setData({
					appMsg: { type: "err", show: true },
				})
				/*wx.showModal({
          title: '提示',
          content: `${error},是否重试?`,
          success: res => {
            if (res.confirm) {
              this.getElements(id, u)
            } else if (res.cancel) {
              wx.switchTab({
                url: '/pages/home/index'
              })
            }
          }
        })*/
			})
	},
	/**
	 * @see 授权事件
	 */
	bindgetuserinfo(res) {
		let userInfo = res.detail.userInfo
		if (userInfo) {
			this.setData({
				avatar: userInfo.avatarUrl,
			})
		}
		this.nextStep()
	},
	/**
	 * @see 点击活动主页按钮事件
	 */
	nextStep() {
		const { avatar } = this.data
		wx.navigateTo({
			url: `/pages/eventConfiguration/pages/inviteFriends/inviteFriends?avatar=${avatar}`,
		})
	},

	/**
	 * @see 左上角返回事件
	 */
	goBack() {
		const token = wx.getStorageSync("token")
		if (token) {
			wx.switchTab({
				url: "/pages/home/index",
			})
		} else {
			wx.reLaunch({
				url: config.loginPage,
			})
		}
	},

	/**
	 * @see 按钮样式
	 */
	returnBtnStyle({
		borderColor,
		startColor,
		endColor,
		shadowColor,
		transparency,
		isGradient,
	}) {
		let bg = ``
		if (isGradient) {
			bg = `background: linear-gradient(to right, ${startColor},${endColor});`
		} else {
			bg = `background:${startColor}`
		}
		return `
      border:6rpx solid ${borderColor};box-shadow: 0px 2px 10px 3px ${shadowColor};${bg};opacity:${
				1 - transparency / 100
			};
    `
	},
	/**
	 * @see 加载失败,重试
	 */
	clickMsgButton() {
		const { activityIdNumber, captainId } = this.data
		this.setData({
			appMsg: {
				type: "err",
				show: false,
			},
		})
		this.getElements(activityIdNumber, captainId)
	},
	/**
	 * @see 数据统计
	 */
	addData() {
		const { activityId } = this.data
		const request = {
			activityId,
			dataType: 0,
		}
		wx.$API["eventConfiguration/addData"](request)
			.then((res) => {
				console.log("数据统计 -- 浏览次数加一,成功")
			})
			.catch((error) => {
				console.log("数据统计 -- 浏览次数加一,失败", error)
			})
	},
})
